#include <iostream>
#include <string>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
using namespace std;

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        cout << "Incorrect use, correct use :" << endl
             << "        ./server local_ip local_port" << endl;
        return 1;
    }
    // 初始化服务端套接字
    string ip = argv[1];
    uint16_t port = stoi(argv[2]);
    // 网络文件信息
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);

    // 绑定套接字，不需要显式的bind，会在第一次发消息时bind随机端口号

    struct sockaddr_in serveraddr;
    serveraddr.sin_addr.s_addr = inet_addr(ip.c_str());
    serveraddr.sin_port = htons(port);
    serveraddr.sin_family = AF_INET;

    string buffer;
    char serverbuffer[1024];
    while (true)
    {
        cout << "please enter: ";
        getline(cin, buffer);
        // 在发送过程中，端口号随机bind                                // 这里需要目标主机的IP地址和端口号，我们在上面已经有了
        ssize_t n = sendto(sockfd, buffer.c_str(), buffer.size(), 0, (struct sockaddr *)&serveraddr, sizeof(serveraddr));
        if (n > 0)
        {
            struct sockaddr_in addr;
            socklen_t len = sizeof(addr);

            ssize_t m = recvfrom(sockfd, serverbuffer, sizeof(serverbuffer)  -1 , 0, (struct sockaddr *)&addr, &len);
            if(m > 0)
            {
                serverbuffer[m] = 0;
                // cout << "server say# " << serverbuffer << endl;
                cout << serverbuffer;
            }
        }
    }

    close(sockfd);
    return 0;
}